package com.youth.service;

import com.alibaba.fastjson.JSONObject;
import com.youth.config.redis.RedissonDistributedLocker;
import com.youth.entity.po.Order;
import com.youth.entity.po.OrderItem;
import com.youth.entity.po.OrderShipping;
import com.youth.entity.vo.CommodityVO;
import com.youth.entity.vo.OrderVO;
import com.youth.feign.commodity.CommodityFeign;
import com.youth.mapper.IOrderItemMapper;
import com.youth.mapper.IOrderMapper;
import com.youth.mapper.IOrderShippingMapper;
import com.youth.result.ResultBean;
import com.youth.utils.CommonUtils;
import com.youth.utils.OrderUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @ClassName OrderService
 * @Description: TODO
 * @Author dy
 * @Date 2019/10/30 21:14
 **/
@Service
@Slf4j
@CacheConfig(cacheNames = {"order"})
public class OrderService {
    @Autowired
    private IOrderMapper iorderMapper;
    @Autowired
    private IOrderItemMapper iOrderItemMapper;
    @Autowired
    private IOrderShippingMapper iOrderShippingMapper;
    @Autowired
    private IOrderMapper orderMapper;
    @Value("${commodityRedisKeyPrefixName}")
    private String commodityRedisKeyPrefixName;
    @Value("${redissonLockerPrefix}")
    private String redissonLockerPrefix;
    @Autowired
    @Qualifier(value = "objRedisTemplate")
    private RedisTemplate redisTemplate;
    @Value("${orderToCommodityKafkaTopicName}")
    private String orderToCommodityKafkaTopicName;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    @Autowired
    private CommodityFeign commodityFeign;
    @Autowired
    private RedissonDistributedLocker redissonDistributedLocker;

    /**
     * @Description :新增订单
     * @Param: [orderVO]
     * @Return: com.youth.result.ResultBean
     * @Author: Administrator
     * @Date: 2019/11/25 16:54
     */
    public Integer add(OrderVO orderVO) {
        ThreadLocal<Integer> add = new ThreadLocal<>();
        try {
            redissonDistributedLocker.lock(redissonLockerPrefix + orderVO.getOrderItemVO().getTCId());
            add.set(null);
            CommodityVO commodityVO = null;
            Object o = null;
            if (redisTemplate.hasKey(commodityRedisKeyPrefixName + orderVO.getOrderItemVO().getTCId())) {
                o = redisTemplate.opsForValue().get(commodityRedisKeyPrefixName + orderVO.getOrderItemVO().getTCId());
            } else {
                ResultBean byCode = commodityFeign.findByCode(orderVO.getOrderItemVO().getTCId());
                o = byCode.getData();
            }
            //商品查询结果不为空
            if (o != null) {
                commodityVO = (CommodityVO) CommonUtils.objectToJavaBean(o, CommodityVO.class);
                //商品库存大于订单商品数量
                if (commodityVO.getStorageNumber() >= orderVO.getOrderItemVO().getNum()) {
                    add.set(1);
                    kafkaTemplate.send(orderToCommodityKafkaTopicName, JSONObject.toJSONString(orderVO));
                }
            }
        } catch (Exception e) {
            log.info("e.getMessage:{}", e.getMessage());
            throw new RuntimeException("order  add  failed！！！");
        } finally {
            return add.get();
        }
    }

    /**
     * @Description :根据订单id查询订单
     * @Param: [orderId]
     * @Return: com.youth.result.ResultBean
     * @Author: Administrator
     * @Date: 2019/11/25 16:55
     */
    @Transactional
    public ResultBean queryOrderById(String orderId) {
        OrderVO order;
        try {
            order = iorderMapper.selectByPrimaryKey(orderId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBean.returnSelectUnSuccess(e.getMessage());
        }
        return ResultBean.returnSelectSuccess(order);
    }


    /**
     * @Description :修改订单信息
     * @Param: [orderId, test]
     * @Return: com.youth.result.ResultBean
     * @Author: Administrator
     * @Date: 2019/11/25 16:58
     */
    @Transactional
    public ResultBean updateOrder(OrderVO orderVO) {

        Order order = OrderUtils.orderVoToOrder(orderVO);

        if (orderVO.getPayment() != null) {
            order.setPaymentTime(new Date());
        }

        order.setStatus(orderVO.getStatus());
        order.setUpdateTime(new Date());

        if (orderVO.getIsConsign() != null) {
            order.setConsignTime(new Date());
        }

        if (orderVO.getIsEnd() != null) {
            order.setEndTime(new Date());
        }

        if (orderVO.getIsClose() != null) {
            order.setCloseTime(new Date());
        }

        OrderShipping orderShipping = OrderUtils.orderShippingVOToOrderShipping(orderVO.getOrderShippingVO());
        orderShipping.setUpdateTime(new Date());


        OrderItem orderItem = OrderUtils.orderItemVOToOrderItem(orderVO.getOrderItemVO());

        try {
            iorderMapper.updateByOrderId(order);

            iOrderShippingMapper.updateOrderShipping(orderShipping);

            iOrderItemMapper.updateByOrderId(orderItem);

        } catch (Exception e) {
            e.printStackTrace();
            return ResultBean.returnUpdateUnSuccess(e.getMessage());
        }
        return ResultBean.returnUpdateSuccess("ok");
    }

    /**
     * @Description :删除订单
     * @Param: [orderId]
     * @Return: com.youth.result.ResultBean
     * @Author: Administrator
     * @Date: 2019/11/26 11:33
     */
    @Transactional
    public ResultBean deleteOrderById(String orderId) {
        try {
            int i = iorderMapper.deleteOrderById(orderId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBean.returnUpdateUnSuccess(e.getMessage());
        }
        return ResultBean.returnUpdateSuccess("ok");
    }

    /**
     * @Description :用户订单查询
     * @Param: [userId]
     * @Return: com.youth.result.ResultBean
     * @Author: Administrator
     * @Date: 2019/11/26 11:39
     */
    @Transactional
    public ResultBean getOrdersByUserId(String userId) {
        List<Order> orderList;
        try {
            orderList = iorderMapper.getOrdersByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBean.returnUpdateUnSuccess(e.getMessage());
        }
        return ResultBean.returnUpdateSuccess(orderList);
    }
}